﻿using ServerUtils;
using System;
using System.ServiceModel;

namespace DemoServiceLibrary
{
    [ServiceBehavior(
        InstanceContextMode = InstanceContextMode.Single, 
        UseSynchronizationContext = false, 
        ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class ServerInfoService : WCFServiceWithInvoker, IServerInfoService
    {
        private readonly IServerInfoProvider serverInfoProvider;

        public ServerInfoService()
            : base("ServerInfoService")
        {
        }

        public ServerInfoService(IServerInfoProvider serverInfoProvider)
            : this()
        {
            this.serverInfoProvider = serverInfoProvider;
        }

        // Using an Operation
        //public GetServerInfoResult GetServerInfo(string parameter)
        //{
        //    var operation = new GetServerInfoOperation(this.serverInfoProvider, parameter);
        //    return this.Invoke(operation);
        //}

        // Using a Func
        public GetServerInfoResult GetServerInfo(string parameter)
        {
            return this.Invoke<GetServerInfoResult>(() =>
                {
                    // simulate a server error
                    if (parameter == "server-error-test")
                    {
                        throw new Exception(parameter);
                    }

                    // simulate a failed operation
                    if (parameter == "failed-test")
                    {
                        return new GetServerInfoResult { ResultType = OperationResultType.Failed, Message = parameter };
                    }

                    var serverInfo = this.serverInfoProvider.GetServerInfo();
                    return new GetServerInfoResult { ResultType = OperationResultType.Succeed, Data = serverInfo };
                },
                parameter);
        }
    }
}
